package com.imti.recyclerviewdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.imti.recyclerviewdemo.MyAdapter.MyHolder;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyHolder>
{

    private List<ContactModel> data;

    //LayoutInflater.from(context).inflate()
    //Activity中传入的this
    private Context context;

    //始终存在的，并且需要创建之初就要有的数据通过构造方法传入
    public MyAdapter(Context context)
    {
        this.context = context;
    }
    //一开始可以没有，或者后续才会有的数据，可以通过set方法传入
    public void setData(List<ContactModel> data)
    {
        this.data = data;
    }

    //创建ViewHolder对象，并且传入条目布局控件对象
    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        return new MyHolder(LayoutInflater.from(context).inflate(R.layout.list_item_contact, null));
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyHolder holder, int position)
    {
        holder.contactName.setText(data.get(position).getContactName());
        holder.contactIcon.setImageResource(data.get(position).getContactIconResId());

        //设置条目点击事件同ListView.setOnItemClickListener
        //对ViewHolder.itemView设置点击事件，与ListView.setOnItemClickListener效果相同
        holder.itemView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Toast.makeText(context, "点击了：" + data.get(position).getContactName(),
                    Toast.LENGTH_SHORT).show();
            }
        });

        holder.contactIcon.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Toast.makeText(context, data.get(position).getContactName() + "的头像",
                    Toast.LENGTH_SHORT).show();
            }
        });
    }

    //BaseAdapter.getCount()
    @Override
    public int getItemCount()
    {
        return null != data ? data.size() : 0;
    }

    class MyHolder extends RecyclerView.ViewHolder
    {

        TextView contactName;

        ImageView contactIcon;

        public MyHolder(@NonNull View itemView)
        {
            super(itemView);
            //获取条目布局子控件
            contactName = itemView.findViewById(R.id.list_item_contact_name);
            contactIcon = itemView.findViewById(R.id.list_item_contact_icon);
        }
    }
}
